package com.stylefeng.guns.modular.wz.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.common.constant.Consts;
import com.stylefeng.guns.common.persistence.dao.WzCheckRecordMapper;
import com.stylefeng.guns.common.persistence.dao.WzUserFixedInfoMapper;
import com.stylefeng.guns.common.persistence.dao.WzUserInfoMapper;
import com.stylefeng.guns.common.persistence.model.WzCheckRecord;
import com.stylefeng.guns.common.persistence.model.WzUser;
import com.stylefeng.guns.common.persistence.model.WzUserFixedInfo;
import com.stylefeng.guns.common.persistence.model.WzUserInfo;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.modular.wz.dao.WzUserDao;
import com.stylefeng.guns.modular.wz.service.IWzUserService;
import com.stylefeng.guns.modular.wz.warpper.WzUserWarpper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 用户控制器
 *
 * @author fengshuonan
 * @Date 2018-03-29 15:26:10
 */
@Controller
@RequestMapping("/wzUser")
public class WzUserController extends BaseController {

    private String PREFIX = "/wz/wzUser/";

    @Autowired
    private IWzUserService wzUserService;
    @Autowired
    private WzUserDao wzUserDao;

    @Autowired
    private WzUserInfoMapper wzUserInfoMapper;

    @Autowired
    private WzUserFixedInfoMapper wzUserFixedInfoMapper;

    @Autowired
    private WzCheckRecordMapper wzCheckRecordMapper;

    /**
     * 跳转到用户首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "wzUser.html";
    }

    /**
     * 跳转到添加用户
     */
    @RequestMapping("/wzUser_add")
    public String wzUserAdd() {
        return PREFIX + "wzUser_add.html";
    }

    /**
     * 跳转到用户信息
     * <p>
     * <p>
     * status：1-正常；2-实名认证中；3-实名认证驳回；4-实名认证通过；5-商户认证中；6-商户认证驳回；7-商户认证通过
     */
    @RequestMapping("/userInfo/{wzUserId}")
    public String userInfo(@PathVariable Long wzUserId, Model model) {
        WzUser user = wzUserService.selectById(wzUserId);
        Long userCode = user.getUserCode();
        model.addAttribute("role", user.getRole());
        int status = user.getStatus();
        List<WzUserInfo> userInfo = wzUserInfoMapper.selectList(new EntityWrapper<WzUserInfo>().eq("user_code", userCode));
        WzUserFixedInfo fixedInfo = wzUserFixedInfoMapper.selectList(new EntityWrapper<WzUserFixedInfo>().eq("user_code", userCode)).get(0);
        model.addAttribute("status", status);
        if (userInfo.size() == 0) {
            model.addAttribute("hasInfo", 0);
            if (status != 1 && status != 3) {
                model.addAttribute("fixedInfo", fixedInfo);
                model.addAttribute("idCardFrontUrl", Consts.DOMAIN + fixedInfo.getIdCardFrontUrl());
                model.addAttribute("idCardBackUrl", Consts.DOMAIN + fixedInfo.getIdCardBackUrl());
                return PREFIX + "wzUser_userInfo.html";
            } else {
                return PREFIX + "wzUser_noneInfo.html";
            }
        } else {
            model.addAttribute("hasInfo", 1);
            model.addAttribute("userInfo", userInfo);
            if (status != 1 && status != 3) {
                model.addAttribute("fixedInfo", fixedInfo);
                model.addAttribute("idCardFrontUrl", Consts.DOMAIN + fixedInfo.getIdCardFrontUrl());
                model.addAttribute("idCardBackUrl", Consts.DOMAIN + fixedInfo.getIdCardBackUrl());
            }
            return PREFIX + "wzUser_userInfo.html";
        }
    }


    /**
     * 跳转到商户信息
     * <p>
     * status：1-正常；2-实名认证中；3-实名认证驳回；4-实名认证通过；5-商户认证中；6-商户认证驳回；7-商户认证通过
     */
    @RequestMapping("/merchantInfo/{wzUserId}")
    public String merchantInfo(@PathVariable Long wzUserId, Model model) {
        WzUser user = wzUserService.selectById(wzUserId);
        Long userCode = user.getUserCode();
        model.addAttribute("role", user.getRole());
        int status = user.getStatus();
        model.addAttribute("status", status);
        List<WzUserInfo> merchantInfo = wzUserInfoMapper.selectList(new EntityWrapper<WzUserInfo>().eq("user_code", userCode));
        if (status == 5 || status == 7) {
            WzUserFixedInfo fixedInfo = wzUserFixedInfoMapper.selectList(new EntityWrapper<WzUserFixedInfo>().eq("user_code", userCode)).get(0);
            model.addAttribute("MerchantLicenseUrl", Consts.DOMAIN + fixedInfo.getMerchantLicenseUrl());
            model.addAttribute("fixedInfo", fixedInfo);
        }
        if (merchantInfo.size() > 0) {
            model.addAttribute("hasInfo", 1);
        } else {
            model.addAttribute("hasInfo", 0);
        }
        model.addAttribute("userCode", userCode);
        model.addAttribute("merchantInfo", merchantInfo);
        return PREFIX + "wzUser_merchantInfo.html";

    }


    /**
     * 跳转到修改用户
     */
    @RequestMapping("/wzUser_update/{wzUserId}")
    public String wzUserUpdate(@PathVariable Integer wzUserId, Model model) {
        WzUser wzUser = wzUserService.selectById(wzUserId);
        model.addAttribute("item", wzUser);
        LogObjectHolder.me().set(wzUser);
        return PREFIX + "wzUser_edit.html";
    }

    /**
     * 获取用户列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(@RequestParam(required = false) String nickName, Integer role, Integer status) {
        List<Map<String, Object>> userList = wzUserDao.selectWzUsers(null, nickName, role, status);
        return new WzUserWarpper(userList).warp();
    }

    /**
     * 新增用户
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(WzUser wzUser) {
        wzUserService.insert(wzUser);
        return super.SUCCESS_TIP;
    }

    /**
     * 删除用户
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer wzUserId) {
        wzUserService.deleteById(wzUserId);
        return SUCCESS_TIP;
    }

    /**
     * 修改用户
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(WzUser wzUser) {
        wzUserService.updateById(wzUser);
        return super.SUCCESS_TIP;
    }

    /**
     * 用户详情
     */
    @RequestMapping(value = "/detail/{wzUserId}")
    @ResponseBody
    public Object detail(@PathVariable("wzUserId") Integer wzUserId) {
        return wzUserService.selectById(wzUserId);
    }

    /**
     * 删除商户信息
     */
    @RequestMapping(value = "/deleteMerchantInfo")
    @ResponseBody
    public Object deleteMerchantInfo(@RequestParam Long userInfoId) {
        wzUserInfoMapper.deleteById(userInfoId);
        return SUCCESS_TIP;
    }

    /**
     * 更新商户信息
     */
    @RequestMapping(value = "/updateMerchantInfo")
    @ResponseBody
    public Object updateMerchantInfo(WzUserInfo wzUserInfo, String userInfoId, String merchantInfo) {
        wzUserInfo.setUserInfoId(Long.parseLong(userInfoId));
        JSONObject json = JSONObject.parseObject(merchantInfo);
        wzUserInfo.setMerchantTel(json.getString("merchantTel"));
        wzUserInfo.setMerchantAddress(json.getString("merchantAddress"));
        wzUserInfo.setMerchantEmail(json.getString("merchantEmail"));
        wzUserInfo.setMerchantWebsite(json.getString("merchantWebsite"));
        wzUserInfo.setMerchantLongitude(json.getString("merchantLongitude"));
        wzUserInfo.setMerchantLatitude(json.getString("merchantLatitude"));
        wzUserInfoMapper.updateById(wzUserInfo);
        return super.SUCCESS_TIP;
    }

    /**
     * 添加商户信息
     */
    @RequestMapping(value = "/addMerchantInfo")
    @ResponseBody
    public Object addMerchantInfo(WzUserInfo wzUserInfo, String userCode, String merchantInfo) {
        wzUserInfo.setUserInfoId(Long.parseLong(userCode));
        JSONObject json = JSONObject.parseObject(merchantInfo);
        wzUserInfo.setMerchantTel(json.getString("merchantTel"));
        wzUserInfo.setMerchantAddress(json.getString("merchantAddress"));
        wzUserInfo.setMerchantEmail(json.getString("merchantEmail"));
        wzUserInfo.setMerchantWebsite(json.getString("merchantWebsite"));
        wzUserInfo.setMerchantLongitude(json.getString("merchantLongitude"));
        wzUserInfo.setMerchantLatitude(json.getString("merchantLatitude"));
        wzUserInfoMapper.insert(wzUserInfo);
        return super.SUCCESS_TIP;
    }

    /**
     * 认证账户
     * <p>
     * role 1-用户；2-实名用户;3-商户
     * <p>
     * status：1-正常；2-实名认证中；3-实名认证驳回；4-实名认证通过；5-商户认证中；6-商户认证驳回；7-商户认证通过
     */
    @RequestMapping(value = "/authentication")
    @ResponseBody
    public Object authentication(@RequestParam String userCode, String success, String role, String status, String idCard) {
        int count = wzUserFixedInfoMapper.selectCount(new EntityWrapper<WzUserFixedInfo>().eq("id_card", idCard));
        if (count > 1) {
            return super.SUCCESS_TIP.fail("身份证重复！无法进行认证");
        } else {
            WzUser user = wzUserService.selectOne(new EntityWrapper<WzUser>().eq("user_code", Long.parseLong(userCode)));
            if ("success".equals(success) && "3".equals(role) && "5".equals(status)) {
                user.setStatus(7);
            } else if ("success".equals(success) && "1".equals(role) && "2".equals(status)) {
                user.setStatus(4);
                user.setRole(2);
            } else if ("success".equals(success) && "1".equals(role) && "5".equals(status)) {
                user.setStatus(7);
                user.setRole(3);
            } else if ("fail".equals(success) && "3".equals(role) && "5".equals(status)) {
                user.setStatus(6);
            } else if ("fail".equals(success) && "1".equals(role) && "2".equals(status)) {
                user.setStatus(3);
            } else if ("fail".equals(success) && "1".equals(role) && "5".equals(status)) {
                user.setStatus(6);
            }
            wzUserService.updateById(user);
            return super.SUCCESS_TIP;
        }
    }

    /**
     * 审核记录.
     * <p>
     * role: 1-用户；2-实名用户;3-商户
     * <p>
     * type:1-广告；2-调查问卷；3-新闻;4-实名认证；5-商户认证,
     * <p>
     * status：1-正常；2-实名认证中；3-实名认证驳回；4-实名认证通过；5-商户认证中；6-商户认证驳回；7-商户认证通过
     */
    @RequestMapping(value = "/wzCheckRecord")
    @ResponseBody
    public Object wzCheckRecord(@RequestParam String userCode, String success, String role, String status) {
        WzCheckRecord record = new WzCheckRecord();
        record.setCheckObjectId(Long.parseLong(userCode));
        if ("success".equals(success) && "3".equals(role) && "5".equals(status)) {
            record.setType(5);
            record.setCheckResult(1);
        } else if ("fail".equals(success) && "3".equals(role) && "5".equals(status)) {
            record.setType(5);
            record.setCheckResult(0);
        } else if ("success".equals(success) && "1".equals(role) && "2".equals(status)) {
            record.setType(4);
            record.setCheckResult(1);
        } else if ("fail".equals(success) && "1".equals(role) && "2".equals(status)) {
            record.setType(4);
            record.setCheckResult(0);
        } else if ("success".equals(success) && "1".equals(role) && "5".equals(status)) {
            record.setType(4);
            record.setCheckResult(1);
        } else if ("fail".equals(success) && "1".equals(role) && "5".equals(status)) {
            record.setType(4);
            record.setCheckResult(0);
        }
        record.setUserId(ShiroKit.getUser().getId());
        record.setCheckName(ShiroKit.getUser().getName());
        record.setCheckTime(new Date());
        wzCheckRecordMapper.insert(record);
        return null;
    }

}
